package com.benjaminwan.read.free.utils

import androidx.fragment.app.Fragment
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.viewmodel.state
import com.benjaminwan.read.free.common.DEFAULT_EXT
import com.benjaminwan.read.free.common.defaultPath
import com.benjaminwan.read.free.ui.main.MainViewModel
import java.io.File
import java.util.*

fun Fragment.saveFile(mainVM: MainViewModel) {
    val saveFileName = "${Date().format("MMddHHmmss")}"
    FileUtils.createOrExistsDir(defaultPath)
    requireContext().showFileNameInputDialog(
        R.string.dialog_file_name_title,
        R.string.dialog_file_name_hint,
        saveFileName,
        { dialog, which ->
            val input = dialog.inputEditText?.text.toString()
            val filePath = "$defaultPath${File.separator}$input$DEFAULT_EXT"
            if (saveJson(filePath, mainVM)) {
                showXToastSuccess(R.string.msg_save_success)
            } else {
                showXToastError(R.string.msg_save_failed)
            }
            dialog.dismiss()
        },
        { dialog, which ->
            dialog.inputEditText?.setText(saveFileName)
            dialog.inputEditText?.setSelection(saveFileName.length)
        })
}

fun Fragment.shareSaveFile(mainVM: MainViewModel) {
    val saveFileName = "${Date().format("MMddHHmmss")}"
    FileUtils.createOrExistsDir(defaultPath)
    requireContext().showFileNameInputDialog(
        R.string.dialog_file_name_title,
        R.string.dialog_file_name_hint,
        saveFileName,
        { dialog, which ->
            val input = dialog.inputEditText?.text.toString()
            val filePath = "$defaultPath${File.separator}$input$DEFAULT_EXT"
            if (saveJson(filePath, mainVM)) {
                requireContext().shareFile(filePath)
            }
            dialog.dismiss()
        },
        { dialog, which ->
            dialog.inputEditText?.setText(saveFileName)
            dialog.inputEditText?.setSelection(saveFileName.length)
        })
}

fun saveJson(
    filePath: String,
    mainVM: MainViewModel
): Boolean {
    val main = mainVM.state
    val json = toActionJsonByMoshi(main.script)
    return FileIOUtils.writeFileFromString(filePath, json)
}